package manager

import (
	"gitee.com/go-web-2/web_framework/context"
	"gitee.com/go-web-2/web_framework/session"
	"gitee.com/go-web-2/web_framework/session/propagator"
	"gitee.com/go-web-2/web_framework/session/redis"
	redis2 "github.com/redis/go-redis/v9"
	"time"
)

// Manager 胶水作用，方便用户操作
type Manager struct {
	session.Store
	session.Propagator
}

func (m *Manager) InitSession(ctx *context.Context, id string) (session.Session, error) {
	sess, err := m.Generate(ctx, id)
	if err != nil {
		return nil, err
	}
	err = m.Inject(ctx.W, id)
	if err != nil {
		return nil, err
	}
	return sess, nil
}

func (m *Manager) GetSession(ctx *context.Context) (session.Session, error) {
	sid, err := m.Extract(ctx.R)
	if err != nil {
		return nil, err
	}
	var sess session.Session
	sess, err = m.Get(ctx, sid)
	if err != nil {
		return nil, err
	}
	return sess, nil
}

func (m *Manager) RemoveSession(ctx *context.Context, id string) error {
	err := m.Remove(ctx, id)
	if err != nil {
		return err
	}
	return m.Delete(ctx.W)
}

func (m *Manager) RefreshSession(ctx *context.Context, id string) error {
	return m.Refresh(ctx, id)
}

func NewManager(cmd redis2.Cmdable, prefix string, duration time.Duration, cookieName string) *Manager {
	return &Manager{
		Store:      redis.NewRedisStore(cmd, prefix, duration),
		Propagator: propagator.NewPropagator(cookieName, duration),
	}
}
